package handlerthread.zjitc.net.androidhomeworkhandlerthread;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 作业使用HandleThread 下载网络图片  显示出来
 */
public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    //使用数组方式存放图片地址
    private String[] url = {
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572192369491&di=e92234d5e57f9026c2dcb7e255b67d18&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201508%2F06%2F20150806163534_C2mS8.jpeg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572192354285&di=965fb0838814b83f8c750ced3e068b3b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201601%2F16%2F20160116173125_Qcw23.jpeg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572192349214&di=ecfe6d9be3aebbe2473d77288e07becc&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201404%2F15%2F20140415204434_wBRB2.jpeg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572192322278&di=6ee4629dc86c8539d724b949e5e81fc7&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ff1450573c09b0128c64b7c8f94c412d399a1503817779e-GqjnkT_fw658",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572192383604&di=8302ac861788b2479d4ab107c3adeb7d&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F4fbb6c708220209933c21d5f397ac9c94c4f89f598891-Dvnyxg_fw658",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572192976238&di=4edfe5543f381a1c5ee64b3faebae9c2&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201412%2F09%2F20141209153445_CVWVj.thumb.700_0.jpeg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572193010326&di=fd9a3f24de71f555face089a1f73dec2&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201504%2F06%2F20150406H5549_KvHSC.jpeg"
    };
    /**
     * Handler步骤1：在主线程中 通过匿名内部类 创建Handler类对象
     */
    private Handler mUIHandler;
    private HandlerThread handlerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.iv);
        /**
         * 步骤一：创建handlerthread实例对象
         * 传入参数=线程名字   作用：标记该线程
         */
        handlerThread = new HandlerThread("downloadImage");

        /**
         * 步骤二：启动线程
         */
        handlerThread.start();

        /**
         * 步骤三：创建工作线程handle&复写handlerMessage（）
         * 作用：关联handlerThread的Looper对象、实现消息处理操作&与其他线程进行通信
         * 注：消息处理操作（handlerMessage（））的执行线程=mhandlerMessage所创建的工作线程中执行
         */
        mUIHandler = new Handler() {
            /**
             *通过复写handleMessage（）从而确定更新Ui的操作
             * @param msg
             */
            @Override
            public void handleMessage(Message msg) {
//            需要执行的UI操作
                ImageModel model = (ImageModel) msg.obj;
                imageView.setImageBitmap(model.getBitmap());
            }
        };

        /**
         * 构建异步handler
         * Callback() 运行子线程
         */
        Handler childHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //在子线程中进行网络请求
                Bitmap bitmap = downloadUrlBitmap(url[msg.what]);

                ImageModel imageModel = new ImageModel();
                imageModel.setBitmap(bitmap);
                imageModel.setUrl(url[msg.what]);
                /**
                 * 步骤四：使用工作线程handler向工作线程的消息队列发送消息
                 * 在工作线程中，当消息循环时取出对应消息&在工作线程执行相关操作
                 */
                //a.定义要发送的消息
                Message msg1 = new Message();
                msg1.what = msg.what; //消息的标识
                msg1.obj = imageModel;  //消息的存放
                 //b.通过handler发送的消息到其绑定的消息队列   通知主线程更新UI
                mUIHandler.sendMessage(msg1);
                return false;
            }
        });
        //每隔一秒去更新图片
        for (int i = 0; i < url.length; i++) {
            childHandler.sendEmptyMessageDelayed(i, 1000 * i);
        }
    }

    /**
     * 该ChildCallback运行子线程
     */
//    class ChildCallback implements Handler.Callback {
//        @Override
//        public boolean handleMessage(Message msg) {
            //在子线程中进行网络请求
//            Bitmap bitmap = downloadUrlBitmap(url[msg.what]);
//
//            ImageModel imageModel = new ImageModel();
//            imageModel.setBitmap(bitmap);
//            imageModel.setUrl(url[msg.what]);
            /**
             * 步骤四：使用工作线程handler向工作线程的消息队列发送消息
             * 在工作线程中，当消息循环时取出对应消息&在工作线程执行相关操作
             */
            //a.定义要发送的消息
//            Message msg1 = new Message();
//            msg1.what = msg.what; //消息的标识
//            msg1.obj = imageModel;  //消息的存放
            /*
            b.通过handler发送的消息到其绑定的消息队列
            通知主线程更新UI
             */
//            mUIHandler.sendMessage(msg1);
//            return false;
//        }
//    }

    /**
     * 网络请求
     *
     * @param urlString
     * @return
     */
    private Bitmap downloadUrlBitmap(String urlString) {
        HttpURLConnection urlConnection = null;
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }


}
